import appSearch from '@/core/app-search';
import { reactive, ref, toRefs } from 'vue';
import path from 'path';
import { getGlobal } from '@electron/remote';
import { nativeImage, ipcRenderer } from 'electron';
import commonConst from '@/common/utils/commonConst';
import PluginHandler from '@/core/plugin-handler';
import optionsManager from './options';
import { exec } from 'child_process';
import searchManager from './search';
import { message } from 'ant-design-vue';
import { PLUGIN_INSTALL_DIR as baseDir } from '@/common/constans/renderer';

const createPluginManager = (): any => {
  // 插件实例
  const pluginInstance = new PluginHandler({
    baseDir,
  });
  // app列表
  const appList: any = ref([]);
  // 一些响应式代码
  const state: any = reactive({
    appList: [],
    plugins: [],
    localPlugins: [],
    currentPlugin: {},
    pluginLoading: false,
    pluginHistory: [],
  });
  // 初始化插件
  const initPlugins = async () => {
    appList.value = await appSearch(nativeImage);
    initLocalStartPlugin();
  };

  const { searchValue, onSearch, setSearchValue, placeholder } =
    searchManager();

  window.updatePlugin = ({ currentPlugin }: any) => {
    state.currentPlugin = currentPlugin;
    getGlobal('LOCAL_PLUGINS').updatePlugin(currentPlugin);
  };

  window.setCurrentPlugin = ({ currentPlugin }) => {
    state.currentPlugin = currentPlugin;
    setSearchValue('');
  };

  // 初始化程序
  window.initRubick = () => {
    state.currentPlugin = {};
    setSearchValue('');
    setOptionsRef([]);
    window.setSubInput({ placeholder: '' });
  };

  window.pluginLoaded = () => {
    state.pluginLoading = false;
  };

  window.searchFocus = (args, strict) => {
    ipcRenderer.send('msg-trigger', {
      type: 'removePlugin',
    });
    window.initRubick();
    searchFocus(args, strict);
  };

  /**
   * 打开一个插件
   * @param plugin
   * @param option
   */
  const openPlugin = async (plugin, option) => {
    if (plugin.pluginType === 'ui' || plugin.pluginType === 'system') {
      if (state.currentPlugin && state.currentPlugin.name === plugin.name) {
        ipcRenderer.sendSync('msg-trigger', {
          type: 'showMainWindow',
        });
        return;
      }
      await loadPlugin(plugin);
      ipcRenderer.sendSync('msg-trigger', {
        type: 'openPlugin',
        data: JSON.parse(
          JSON.stringify({
            ...plugin,
            ext: plugin.ext || {
              code: plugin.feature.code,
              type: plugin.cmd.type || 'text',
              payload: null,
            },
          })
        ),
      });
    }
    // 如果是系统程序
    if (plugin.pluginType === 'app') {
      try {
        exec(plugin.action);
      } catch (e) {
        message.error('启动应用出错，请确保启动应用存在！');
      }
    }
    // 初始化插件
    window.initRubick();
    // 添加到历史记录中
    changePluginHistory({
      ...plugin,
      ...option,
    });
  };

  // 改变插件的顺序
  const changePluginHistory = (plugin) => {
    // 先删除之前的插件
    state.pluginHistory.forEach((p, index) => {
      if (p.name === plugin.name) {
        state.pluginHistory.splice(index, 1);
      }
    });
    // 历史插件最多容纳8个
    state.pluginHistory.unshift(plugin);
    if (state.pluginHistory.length > 8) {
      state.pluginHistory.pop();
    }
  };

  const {
    options,
    searchFocus,
    clipboardFile,
    setOptionsRef,
    clearClipboardFile,
    readClipboardContent,
  } = optionsManager({
    searchValue,
    appList,
    openPlugin,
    currentPlugin: toRefs(state).currentPlugin,
  });

  // 初始化本地启动的插件
  const initLocalStartPlugin = () => {
    const result = ipcRenderer.sendSync('msg-trigger', {
      type: 'dbGet',
      data: {
        id: 'rubick-local-start-app',
      },
    });
    if (result && result.value) {
      appList.value.push(...result.value);
    }
  };

  // 删除本地插件
  window.removeLocalStartPlugin = ({ plugin }) => {
    appList.value = appList.value.filter((app) => app.desc !== plugin.desc);
  };

  // 添加本地插件
  window.addLocalStartPlugin = ({ plugin }) => {
    window.removeLocalStartPlugin({ plugin });
    appList.value.push(plugin);
  };
  /**
   * 加载插件
   * @param plugin
   */
  const loadPlugin = async (plugin) => {
    // 设施搜索关键词为空
    setSearchValue('');
    ipcRenderer.send('msg-trigger', {
      type: 'setExpendHeight',
      data: 60,
    });
    state.pluginLoading = true;
    state.currentPlugin = plugin;
    // 自带的插件不需要检测更新
    if (plugin.name === 'rubick-system-feature') return;
    await pluginInstance.upgrade(plugin.name);
    state.pluginLoading = false;
  };

  window.loadPlugin = (plugin) => loadPlugin(plugin);

  const changeSelect = (select) => {
    state.currentPlugin = select;
  };

  // 获取插件信息
  const getPluginInfo = async ({ pluginName, pluginPath }) => {
    const pluginInfo = await pluginInstance.getAdapterInfo(
      pluginName,
      pluginPath
    );
    return {
      ...pluginInfo,
      icon: pluginInfo.logo,
      indexPath: commonConst.dev()
        ? 'http://localhost:8081/#/'
        : `file://${path.join(pluginPath, '../', pluginInfo.main)}`,
    };
  };

  const addPlugin = (plugin: any) => {
    state.plugins.unshift(plugin);
  };

  const removePlugin = (plugin: any) => {
    // TODO
  };

  return {
    ...toRefs(state),
    initPlugins,
    addPlugin,
    removePlugin,
    onSearch,
    getPluginInfo,
    openPlugin,
    changeSelect,
    options,
    searchValue,
    placeholder,
    searchFocus,
    setSearchValue,
    clipboardFile,
    clearClipboardFile,
    readClipboardContent,
  };
};

export default createPluginManager;
